<?php

namespace app\admin\controller\device;

use app\admin\model\device\Category;
use app\admin\model\device\DeviceModel;
use app\common\controller\Backend;
use think\Db;

/**
 * 设备管理
 *
 * @icon fa fa-circle-o
 */
class Device extends Backend
{

    /**
     * Device模型对象
     * @var \app\admin\model\device\Device
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\device\Device;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['category','user','model'])
                    ->where($where)
                    ->where('device.deletetime',$this->model::DELETE_TIME)
                    ->order($sort, $order)
                    ->paginate($limit);

//            foreach ($list as $row) {
//
//
//            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $rule = [
                    'category_id' => 'require|number|>:0',
                    'model_id' => 'require|number|>:0',
                    'num' => 'require|number|>:0'
                ];
                $this->validate($params,$rule);
                $categoryModel = new Category();
                $category = $categoryModel->field('id,name,speed,hardness,duration,prefix')
                    ->where('id',$params['category_id'])
                    ->where('deletetime',$categoryModel::DELETE_TIME)
                    ->find();
                if(!$category){
                    $this->error('设备类型不存在');
                }

                $deModel = new DeviceModel();
                if (!$deModel->checkIsExist($params['model_id'])) {
                    $this->error('设备型号不存在');
                }

                Db::startTrans();

                try {
                    $data = [];
                    for ($i=0; $i<$params['num']; $i++) {
                        $prefix = $category['prefix']?$category['prefix'].'-':'';
                        $data[] = [
                            'category_id' => $params['category_id'],
                            'model_id' => $params['model_id'],
                            'name' => $prefix.date('YmdHis').'-'.rand(1000,9999),
                            'identifier_code' => $this->model->generateIdentifierCode(),
                            'device_sn' => $this->model->generateDeviceSn(),
                            'speed' => $category['speed'],
                            'hardness' => $category['hardness'],
                            'duration' => $category['duration'],
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                    $this->model->saveAll($data);

                    Db::commit();
                }catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $rule = [
                    'id' => 'require|number|>:0',
                    'category_id' => 'require|number|>:0',
                    'model_id' => 'require|number|>:0',
                    'speed' => 'require|number|>=:0',
                    'hardness' => 'require|number|>=:0',
                    'duration' => 'require|number|>=:0',
                    'name' => 'require|max:50',
                ];
                $this->validate($params, $rule);
                if(!$this->model->checkIsExist($params['id'])){
                    $this->error('设备不存在');
                }

                $result = $this->model
                    ->where('id', $params['id'])
                    ->update($params);

                if (!$result) {
                    $this->error($this->model->getError());
                }
                $this->success();
            }
        }
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }

    public function del($ids=null)
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids || $this->request->post("ids");
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['master_id']) {
            $this->error('设备正在使用中，无法删除');
        }
        $this->model->where('id', $ids)->update(['deletetime' => time()]);

        $this->success();
    }

}
